package com.jrx.anytxn.param.job.cutover.config;

import com.jrx.anytxn.param.config.AnytxnBatchProperties;
import com.jrx.anytxn.param.config.CutoverConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.job.cutover.step.CutoverListener;
import com.jrx.anytxn.param.job.cutover.step.CutoverProcessor;
import com.jrx.anytxn.param.job.cutover.step.CutoverWriter;
import com.jrx.anytxn.param.mapper.ext.ExtPrOrganizationTableMapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.listener.StepExecutionListenerSupport;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 日切任务
 * @author Qingyao Xing
 * @date 2019/9/9 13:28
 */
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
public class CutoverConfiguration {
    Logger logger = LoggerFactory.getLogger(CutoverConfiguration.class);


    @Resource(name = "paramSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private AnytxnBatchProperties anytxnBatchProperties;

    @Autowired
    private CutoverProcessor cutoverProcessor;

    @Autowired
    private CutoverWriter cutoverWriter;

    @Autowired
    private CutoverListener cutoverListener;

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Autowired
    private ExtPrOrganizationTableMapper extPrOrganizationTableMapper;

    @Autowired
    private CutoverConfig cutoverConfig;

    @Bean
    public Job cutoverJob(){
        return jobBuilderFactory.get("cutoverJob").incrementer(new RunIdIncrementer()).listener(cutoverListener)
                .start(checkCutoverStep())
                .next(cutoverStep())
                .build();
    }

    @Bean
    public Step checkCutoverStep() {
        return stepBuilderFactory.get("checkCutoverStep")
                .tasklet(checkCutoverTasklet())
                .build();
    }

    private Tasklet checkCutoverTasklet() {
        return (stepContribution, chunkContext) -> {
            PrOrganizationTable organizationTable = extPrOrganizationTableMapper.selectByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            long nextProcessingDate = organizationTable.getNextProcessingDate().getTime();
            long s = System.currentTimeMillis();
            //业务时间不能比当前系统时间大1天
            if("0".equals(cutoverConfig.getCutFlag()) && nextProcessingDate > s + 60*60*24*1000) {
                throw new RuntimeException("不允许跳批");
            }
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Step cutoverStep(){
        return stepBuilderFactory.get("cutoverStep")
                .<PrOrganizationTable, PrOrganizationTable>chunk(anytxnBatchProperties.getCutoverConfiguration().getChunkLimit())//表示一批处理100条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(cutoverReader())
                .processor(cutoverProcessor)
                .writer(cutoverWriter)
                .transactionManager(platformTransactionManager)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchProperties.getCutoverConfiguration().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<PrOrganizationTable> cutoverReader() {

        MyBatisCursorItemReader<PrOrganizationTable> orgCursorItemReader = new MyBatisCursorItemReader<>();
        orgCursorItemReader.setSaveState(false);
        orgCursorItemReader.setSqlSessionFactory(sqlSessionFactory);
        //查询方法
        orgCursorItemReader.setQueryId("com.jrx.anytxn.param.mapper.ext.ExtPrOrganizationTableMapper" +
                ".selectByStatusAndFlag");
        Map<String,Object> map = new HashMap<>();
        //查询参数设置
        map.put("status", Constant.ORG_STATUS_1);
        map.put("batchInProgressFlag", Constant.ORG_BATCH_FLAG_0);
        orgCursorItemReader.setParameterValues(map);
        //同步reader   线程安全
        SynchronizedItemStreamReader<PrOrganizationTable> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(orgCursorItemReader);
        return synchronizedItemStreamReader;
    }
}
